import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/settings_provider.dart';
import '../providers/todos_provider.dart';
import '../../utils/keyboard_utils.dart';

/// 设置页面
class SettingsPage extends ConsumerWidget {
  const SettingsPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userSettings = ref.watch(userSettingsProvider);
    final themeMode = ref.watch(themeModeProvider);

    return DismissKeyboardScaffold(
      appBar: AppBar(title: const Text('设置'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      child: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // 用户信息卡片
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  const CircleAvatar(radius: 40, child: Icon(Icons.person, size: 40)),
                  const SizedBox(height: 16),
                  Text(userSettings.username, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                  const SizedBox(height: 8),
                  ElevatedButton.icon(
                    onPressed: () {
                      _showEditNameDialog(context, ref, userSettings.username);
                    },
                    icon: const Icon(Icons.edit),
                    label: const Text('修改用户名'),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),

          // 应用设置
          const Text('应用设置', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),

          Card(
            child: Column(
              children: [
                SwitchListTile(
                  title: const Text('通知'),
                  subtitle: const Text('接收应用通知'),
                  value: userSettings.notificationsEnabled,
                  onChanged: (value) {
                    ref.read(userSettingsProvider.notifier).toggleNotifications();
                  },
                ),
                ListTile(
                  leading: Icon(
                    themeMode == ThemeMode.dark
                        ? Icons.dark_mode
                        : themeMode == ThemeMode.light
                        ? Icons.light_mode
                        : Icons.brightness_auto,
                  ),
                  title: const Text('主题模式'),
                  subtitle: Text(_getThemeModeText(themeMode)),
                  trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                  onTap: () {
                    _showThemeModeDialog(context, ref);
                  },
                ),
                ListTile(
                  title: const Text('语言'),
                  subtitle: Text(userSettings.language),
                  trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                  onTap: () {
                    _showLanguageDialog(context, ref);
                  },
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),

          // 数据管理
          const Text('数据管理', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),

          Card(
            child: Column(
              children: [
                ListTile(
                  leading: const Icon(Icons.delete_sweep, color: Colors.orange),
                  title: const Text('清除已完成待办'),
                  subtitle: const Text('删除所有已完成的待办事项'),
                  onTap: () {
                    final completed = ref.read(completedTodosProvider);
                    if (completed == 0) {
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('没有已完成的待办事项')));
                      return;
                    }

                    showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        title: const Text('确认删除'),
                        content: Text('确定要删除$completed个已完成的待办事项吗？'),
                        actions: [
                          TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
                          FilledButton(
                            onPressed: () {
                              ref.read(todosProvider.notifier).clearCompleted();
                              Navigator.pop(context);
                              ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('已清除已完成待办')));
                            },
                            child: const Text('确定'),
                          ),
                        ],
                      ),
                    );
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.refresh, color: Colors.blue),
                  title: const Text('重置应用数据'),
                  subtitle: const Text('恢复到初始状态'),
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        title: const Text('确认重置'),
                        content: const Text('这将删除所有数据并恢复到初始状态，确定要继续吗？'),
                        actions: [
                          TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
                          FilledButton(
                            onPressed: () {
                              // 重置数据
                              ref.invalidate(todosProvider);
                              ref.invalidate(userSettingsProvider);
                              ref.invalidate(themeModeProvider);

                              Navigator.pop(context);
                              ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('应用已重置')));
                            },
                            child: const Text('确定'),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),

          // 关于
          const Text('关于', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),

          Card(
            child: Column(
              children: [
                ListTile(leading: const Icon(Icons.info), title: const Text('版本'), subtitle: const Text('1.0.0')),
                ListTile(
                  leading: const Icon(Icons.code),
                  title: const Text('技术栈'),
                  subtitle: const Text('Flutter + Riverpod + go_router + Dio + rxDart'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String _getThemeModeText(ThemeMode mode) {
    switch (mode) {
      case ThemeMode.light:
        return '浅色';
      case ThemeMode.dark:
        return '深色';
      case ThemeMode.system:
        return '跟随系统';
    }
  }

  void _showEditNameDialog(BuildContext context, WidgetRef ref, String currentName) {
    final controller = TextEditingController(text: currentName);

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('修改用户名'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(labelText: '用户名', border: OutlineInputBorder()),
          autofocus: true,
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
          FilledButton(
            onPressed: () {
              if (controller.text.trim().isNotEmpty) {
                ref.read(userSettingsProvider.notifier).updateUsername(controller.text.trim());
                Navigator.pop(context);
              }
            },
            child: const Text('保存'),
          ),
        ],
      ),
    );
  }

  void _showThemeModeDialog(BuildContext context, WidgetRef ref) {
    final currentThemeMode = ref.read(themeModeProvider);

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择主题模式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('浅色'),
              leading: const Icon(Icons.light_mode),
              trailing: currentThemeMode == ThemeMode.light ? const Icon(Icons.check, color: Colors.blue) : null,
              onTap: () {
                ref.read(themeModeProvider.notifier).state = ThemeMode.light;
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('已切换到浅色主题'), duration: Duration(seconds: 1)));
              },
            ),
            ListTile(
              title: const Text('深色'),
              leading: const Icon(Icons.dark_mode),
              trailing: currentThemeMode == ThemeMode.dark ? const Icon(Icons.check, color: Colors.blue) : null,
              onTap: () {
                ref.read(themeModeProvider.notifier).state = ThemeMode.dark;
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('已切换到深色主题'), duration: Duration(seconds: 1)));
              },
            ),
            ListTile(
              title: const Text('跟随系统'),
              leading: const Icon(Icons.brightness_auto),
              trailing: currentThemeMode == ThemeMode.system ? const Icon(Icons.check, color: Colors.blue) : null,
              onTap: () {
                ref.read(themeModeProvider.notifier).state = ThemeMode.system;
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('已切换到跟随系统主题'), duration: Duration(seconds: 1)));
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showLanguageDialog(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择语言'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('中文'),
              onTap: () {
                ref.read(userSettingsProvider.notifier).updateLanguage('中文');
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('English'),
              onTap: () {
                ref.read(userSettingsProvider.notifier).updateLanguage('English');
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}
